package sk.tramtatiri.data.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.transaction.annotation.Transactional;

import sk.tramtatiri.data.dao.interfaces.UserDao;
import sk.tramtatiri.data.dataobjects.User;

public class UserDaoJPAImp extends AbstractDaoJPAImpl<User> implements UserDao {

	public UserDaoJPAImp() {
		super(User.class);
	}

	@Transactional
	public List<User> findAll() {
		return getJpaTemplate().execute(new JpaCallback<List<User>>() {
			public List<User> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<User> query = em.createQuery("select u from User u", User.class);
				return query.getResultList();
			}
		});
	}
	
	@Transactional
	public User findUserByEmail(final String email) {
		return getJpaTemplate().execute(new JpaCallback<User>() {
			public User doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<User> query = em.createQuery("select u from User u where email='"+email+"'", User.class);
				return query.getSingleResult();
			}
		});
	}

	@Transactional
	public int countAll() {
		return getJpaTemplate().execute(new JpaCallback<Integer>() {

			public Integer doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<Long> query = em.createQuery("select count (u) from User u", Long.class);
				return (query.getSingleResult()).intValue();
			}
		});
	}

	public User findName(String name) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Transactional
	public List<User> findAllByNameExceptMe(final long user_id, final String searchingName) {
		return getJpaTemplate().execute(new JpaCallback<List<User>>() {
			public List<User> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<User> query = em.createQuery("select u from User u where u.id != :userId and LOWER(u.nickname) like '%" + searchingName.trim().toLowerCase() + "%' order by u.nickname", User.class);
				query.setParameter("userId", user_id);
//				query.setParameter("userNick", "'" + searchingName + "'");
				return query.getResultList();
			}
		});
	}

	@Transactional
	public void delete(User o) {
		User u = getJpaTemplate().find(User.class, o.getId());
		getJpaTemplate().remove(u);
	}

}
